package org.jfk.sys.user;

import java.util.List;

import org.apache.log4j.Logger;
import org.jfk.core.model.BaseModel;
import org.jfk.core.model.SqlFilter;
import org.jfk.core.utils.SqlFileUtils;
import org.jfk.sys.dictionary.Dict;
import org.jfk.sys.org.Org;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.Table;
import com.jfinal.plugin.activerecord.TableMapping;

/**
 * 
mysql> show full columns from manager;
+------------+--------------+-----------------+------+-----+---------------------+-----------------------------+---------------------------------+----------+
| Field      | Type         | Collation       | Null | Key | Default             | Extra                       | Privileges                      | Comment  |
+------------+--------------+-----------------+------+-----+---------------------+-----------------------------+---------------------------------+----------+
| id         | int(15)      | NULL            | NO   | PRI | NULL                | auto_increment              | select,insert,update,references |          |
| loginName  | varchar(30)  | utf8_general_ci | NO   |     | NULL                |                             | select,insert,update,references | 登录名   |
| password   | varchar(100) | utf8_general_ci | NO   |     | NULL                |                             | select,insert,update,references | 密码     |
| realName   | varchar(100) | utf8_general_ci | YES  |     | NULL                |                             | select,insert,update,references | 真实姓名 |
| email      | varchar(100) | utf8_general_ci | YES  |     | NULL                |                             | select,insert,update,references | 电子邮箱 |
| mobile     | varchar(100) | utf8_general_ci | YES  |     | NULL                |                             | select,insert,update,references | 手机号码 |
| remark     | longtext     | utf8_general_ci | YES  |     | NULL                |                             | select,insert,update,references | 备注     |
| picture    | blob         | NULL            | YES  |     | NULL                |                             | select,insert,update,references | 头像     |
| createTime | timestamp    | NULL            | NO   |     | 0000-00-00 00:00:00 | on update CURRENT_TIMESTAMP | select,insert,update,references | 创建时间 |
| creator    | int(15)      | NULL            | NO   |     | NULL                |                             | select,insert,update,references | 创建人   |
| status     | varchar(10)  | utf8_general_ci | YES  |     | NULL                |                             | select,insert,update,references | 状态     |
+------------+--------------+-----------------+------+-----+---------------------+-----------------------------+---------------------------------+----------+
 * @author jxf
 * 2014年10月30日
 */

@SuppressWarnings("serial")
public class User extends  BaseModel<User> {
	private static Logger logger = Logger.getLogger(User.class);	
	public static final User dao;
	public static final Table table;
	public static final String tableName;
	static {
		dao = new User();
		table = TableMapping.me().getTable(User.class);
		tableName = table.getName();
	}
	
	public Page<User> paginate(UserController controller){
		String select = " select "+tableName+".*,ot1.loginName creator_loginName,ot2.dict_value status_dict_value,ot3.id orgId,ot3.orgName orgName";
		String from =" from "+tableName;
		String join = " left outer join "+tableName+" ot1 on ot1.id="+tableName+".creator";
		join = join + " left join "+Dict.tableName+" ot2 on ot2.id="+tableName+".status";
		join = join + " left join "+Org.tableName+" ot3 on ot3.id="+tableName+".orgId";
		String where = " where 1=1 ";
		
		SqlFilter filter = controller.genJsonFilter();
		
		//处理列表查询的智能搜索
		String search = controller.getPara("search");	

		if (search != null && !"".equals(search.trim())) {
			SqlFilter searchFilter = new SqlFilter();
			searchFilter.add("and", tableName+".id", "eq", search);
			searchFilter.add("or", tableName+".loginName", "like", search);
			searchFilter.add("or", tableName+".email", "like", search);
			searchFilter.add("or", tableName+".mobile", "like", search);
			searchFilter.end();
			filter.add(searchFilter);
			controller.setAttr("search", search);
		}
		
		//加工request参数
		controller.addPageAttr();
		
		String sqlExceptSelect = from+join+where+filter.sqlText;
		sqlExceptSelect = sqlExceptSelect + controller.sqlSort;
		logger.debug(filter);
		Page<User> page = dao.paginate(controller.currentPage, controller.limit, select, sqlExceptSelect, filter.params.toArray());
		return page;
	}
	
	public User findById(Object id){
		return dao.findFirst("select a.*,b.loginName creator_loginName,c.id orgId,c.orgName orgName"
				+ " from "+tableName+" a "
				+ " left join "+tableName+" b on a.creator=b.id"
				+ " left join "+Org.tableName+" c on a.orgId=c.id"
				+ " where a.id=?",id);
	}
	
	public User findByLoginName(String loginName){
		return dao.findFirst("select a.* from "+tableName+" a where a.loginName = ?", loginName);
		
	}
	
	public List<Record> getUsersByRole(int roleId){
		String sql = SqlFileUtils.readSqlFromFile("sys.getUsersByRole.sql");
		List<Record> users = Db.find(sql,roleId);
		return users;
	}
	
	public List<Record> getRolesByUser(int userId){
		String sql = SqlFileUtils.readSqlFromFile("sys.getRolesByUser.sql");
		List<Record> roles = Db.find(sql,userId);
		return roles;
	}	
}
